All files / src/app/api/admin/loyalty/members/[id] route.ts

0% Statements 0/127
100% Branches 0/0
0% Functions 0/1
0% Lines 0/127

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128                                                                                                                                                                                                                                                               
export const dynamic = "force-dynamic";

import { NextRequest, NextResponse } from 'next/server';
import { } from "next-auth";
import { prisma } from "@/lib/prisma";
import { z } from "zod";
import {
  withAdmin,
  withErrorHandling,
  successResponse,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse } from "@/lib/api";
import { RouteContext } from "@/lib/api/middleware";

const UpdateMemberSchema = z.object({
  currentTierId: z.number().optional(),
  notes: z.string().optional() });

interface RouteParams {
  params: Promise<{ id: string }>;
}

/**
 * GET /api/admin/loyalty/members/[id]
 * Get single member details
 */
async function handleGet(
  request: NextRequest,
  context: RouteContext | undefined
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const { id } = await (context as RouteParams).params;
  const memberId = parseInt(id);

  if (isNaN(memberId)) {
    throw ApiError.badRequest("Invalid member ID");
  }

  const member = await prisma.customerLoyalty.findUnique({
    where: { id: memberId },
    include: {
      user: {
        select: {
          id: true,
          email: true,
          name: true,
          createdAt: true } },
      transactions: {
        orderBy: { createdAt: "desc" },
        take: 20 } } });

  if (!member) {
    throw ApiError.notFound("Member");
  }

  // Get tier info
  let tier = null;
  if (member.currentTierId) {
    tier = await prisma.loyaltyTier.findUnique({
      where: { id: member.currentTierId } });
  }

  return successResponse({
    id: member.id,
    userId: member.userId,
    user: {
      id: member.user.id,
      email: member.user.email,
      name: member.user.name || "N/A" },
    totalPoints: member.totalPoints,
    lifetimePoints: member.lifetimePoints,
    currentTierId: member.currentTierId,
    tier,
    joinedAt: member.user.createdAt,
    recentTransactions: member.transactions });
}

/**
 * PATCH /api/admin/loyalty/members/[id]
 * Update member (tier override, notes)
 */
async function handlePatch(
  request: NextRequest,
  context: RouteContext | undefined
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const { id } = await (context as RouteParams).params;
  const memberId = parseInt(id);

  if (isNaN(memberId)) {
    throw ApiError.badRequest("Invalid member ID");
  }

  const body = await request.json();
  const validationResult = UpdateMemberSchema.safeParse(body);

  if (!validationResult.success) {
    throw ApiError.validation("Invalid data", validationResult.error.issues);
  }

  const validatedData = validationResult.data;

  const member = await prisma.customerLoyalty.findUnique({
    where: { id: memberId } });

  if (!member) {
    throw ApiError.notFound("Member");
  }

  // Validate tier exists if provided
  if (validatedData.currentTierId) {
    const tier = await prisma.loyaltyTier.findUnique({
      where: { id: validatedData.currentTierId } });
    if (!tier) {
      throw ApiError.badRequest("Invalid tier ID");
    }
  }

  const updatedMember = await prisma.customerLoyalty.update({
    where: { id: memberId },
    data: {
      currentTierId: validatedData.currentTierId } });

  return successResponse(updatedMember);
}

export const GET = withErrorHandling(withAdmin(handleGet));
export const PATCH = withErrorHandling(withAdmin(handlePatch));